package com.wesley.controller;


import com.wesley.DemoReddisonApplication;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;


@RestController
@RequestMapping("/test")
public class TestLockController {


    @Autowired
    private RedissonClient redisson;

    private int count = 0;

    @GetMapping("/lock")
    public void testLock() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(() -> {
                RLock testLock = redisson.getLock("testLock");
                try {
                    testLock.lock();
                    count = count + 1;
                    System.out.println(Thread.currentThread().getName() +" = " + count);
                } finally {
                    testLock.unlock();
                }
                countDownLatch.countDown();
            });
            thread.start();
        }

        countDownLatch.await();
        System.out.println("count = " + count);
    }

}
